package com.xxl.job.executor.service.jobhandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Service;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
import com.xxl.job.core.log.XxlJobLogger;

@JobHander(value="CommandJobHandler")
@Service
public class CommandJobHandler extends IJobHandler {
	
	
	@Override
	public ReturnT<String> execute(String... params) throws Exception {		

		String cmdString = "";
		for(int i=0;i<params.length;i++)
		{
			cmdString += params[i].trim() + " ";
		}
		try{
			Process process = Runtime.getRuntime().exec(cmdString);	
			StringBuilder result = new StringBuilder();
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));    
			BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			try {    
				String line;    
				while ((line = reader.readLine()) != null) {    
					result.append("<p>"+line+"</p>");    
				}
				while ((line = error.readLine()) != null)
				{
					result.append("<p>"+line+"</p>"); 
				}
			} catch (IOException e) {    
			    result.append(e.getMessage());    
			}
			
			
			
			XxlJobLogger.log("execute result:" + result);
			process.waitFor();    
			int exit = process.exitValue(); 
			XxlJobLogger.log("execute exit:" + exit);
			if (exit != 0) {    
				return new ReturnT(ReturnT.FAIL_CODE,"退出进程失败");
			} else {    
			    return new ReturnT(ReturnT.SUCCESS_CODE, "执行成功");
			}
		} catch(Exception e){
			return new ReturnT(ReturnT.FAIL_CODE, "执行失败:" + e.getMessage());
		}
	}
	
}
